package dao.impl;

import java.util.List;

 

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
 

import dao.AnswerDao;
import domain.Answer;
import domain.Board;

public class AnswerDaoImpl implements AnswerDao {
/* (non-Javadoc)
 * @see dao.impl.AnwerDao#save(domain.Answer)
 */
public void save(Answer answer){
	try {
		Session session=HibernateSessionFactory.getSession();
		Transaction transaction=session.beginTransaction();
		session.save(answer);
		transaction.commit();
		session.flush();
		session.close();
	} catch (HibernateException e) { 
		e.printStackTrace();
	}
}
 
public void update(Answer answer){
	Session session=HibernateSessionFactory.getSession();
	Transaction transaction=session.getTransaction();
	transaction.begin();
	session.merge(answer);
	transaction.commit();
	session.close();
	
}
/* (non-Javadoc)
 * @see dao.impl.AnwerDao#delete(int)
 */
public void delete(int id){
	Session session=HibernateSessionFactory.getSession();
	Transaction transaction=session.getTransaction();
	transaction.begin();
   Answer anserTemp=(Answer) session.get(Answer.class, id);
   session.delete(anserTemp);
   transaction.commit();
   session.flush();
	if(session != null)
	    session.close();	 
}
public  Answer findById(int id){
	Session session=HibernateSessionFactory.getSession();
	 
   Answer answer=(Answer) session.get(Answer.class, id);
	 
	if(session != null)
	    session.close();
	return answer;
	
}
public List<Answer> list(){
	Session session=HibernateSessionFactory.getSession();
	List<Answer> list;
   Query qr=session.createQuery("from Answer");
	list=qr.list();
	if(session != null)
	    session.close();
	return list;
}
/* (non-Javadoc)
 * @see dao.impl.AnwerDao#listByBoardId(int)
 */
public List<Answer> listByQuestionId(int questionId){
	Session session=HibernateSessionFactory.getSession();
	List<Answer> list;
   Query qr=session.createQuery("from Answer as B where B.question.id=:id order by B.id desc");
    qr.setLong("id", questionId);
	list=qr.list();
	if(session != null)
	    session.close();
	return list;
}
}
